import { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { setDark } from "@/store/slices/theme";
import { Button, Card, Dropdown, Modal } from "antd";
import {
  ExportOutlined,
  CaretDownOutlined,
  SunOutlined,
  MoonOutlined,
} from "@ant-design/icons";
import { ThemeOutlined } from "@/components/extraIcons";
import ThemeModal from "../themeModal";
import { globalConfig } from "@/globalConfig";
import { useNavigate } from "react-router-dom";
import logoImg from "@/common/images/logo.png";
import "./index.less";

const Header = () => {
  const dispatch = useDispatch();

  const navigate = useNavigate();

  const theme = useSelector((state) => state.theme);

  const [modal, contextHolder] = Modal.useModal();

  const [showThemeModal, setShowThemeModal] = useState(false);

  const logout = () => {
    modal.confirm({
      title: "确定要退出系统？",
      okText: "确定",
      onOk: () => {
        window.localStorage.removeItem(globalConfig.SESSION_LOGIN_INFO);
        navigate("/login");
      },
    });
  };

  const loginInfo = JSON.parse(
    window.localStorage.getItem(globalConfig.SESSION_LOGIN_INFO)
  );

  const menuItems = [
    {
      label: "退出登录",
      key: "exit",
      icon: <ExportOutlined />,
      onClick: logout,
    },
  ];

  return (
    <Card className="M-header" variant={false}>
      <div className="header-wrapper">
        <div className="logo-con">
          <img src={logoImg} />
          <span className="logo-text">Vite React Admin</span>
        </div>
        <div className="header-con">
          {theme.dark ? (
            <Button
              icon={<SunOutlined />}
              shape="circle"
              onClick={() => dispatch(setDark(false))}
            ></Button>
          ) : (
            <Button
              icon={<MoonOutlined />}
              shape="circle"
              onClick={() => dispatch(setDark(true))}
            ></Button>
          )}

          {globalConfig.customColorPrimarys &&
            globalConfig.customColorPrimarys.length > 0 && (
              <Button
                icon={<ThemeOutlined />}
                shape="circle"
                onClick={() => setShowThemeModal(true)}
              ></Button>
            )}

          <Dropdown menu={{ items: menuItems }}>
            <div className="user-menu">
              <span>{loginInfo ? loginInfo.nickname : "未登录"}</span>
              <CaretDownOutlined className="arrow" />
            </div>
          </Dropdown>
        </div>
      </div>
      {showThemeModal && (
        <ThemeModal onClose={() => setShowThemeModal(false)} />
      )}
      {contextHolder}
    </Card>
  );
};

export default Header;
